package com.wngbms.fileio.file_transfer;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class FileMmapDemo {

    public static void main(String[] args) {

//        mmapWriteFile();

        mmapPrivate();


    }

    private static void mmapPrivate() {
        try (FileChannel channel = new RandomAccessFile("J:\\mini.txt", "rw").getChannel()) {

            MappedByteBuffer mappedByteBuffer = channel.map(FileChannel.MapMode.PRIVATE, 0, 1024);
            for (int i = 0; i < 1024; i++) {
                mappedByteBuffer.put((byte) (Integer.valueOf('a') + i % 26));
            }

            for (int i = 0; i < 1024; i++) {
                if (i % 50 == 0) {
                    System.out.println();
                }
                System.out.print((char) mappedByteBuffer.get(i));
            }

            mappedByteBuffer.force();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void mmapWriteFile() {
        try (FileChannel channel = new RandomAccessFile("J:\\mini.txt", "rw").getChannel()) {

            MappedByteBuffer mappedByteBuffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, 1024);
            for (int i = 0; i < 1024; i++) {
                mappedByteBuffer.put((byte) (Integer.valueOf('a') + i % 26));
            }
            for (int i = 0; i < 1024; i++) {
                if (i % 50 == 0) {
                    System.out.println();
                }
                System.out.print((char) mappedByteBuffer.get(i));
            }

            mappedByteBuffer.force();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
